<template>
    <div class="compact-container">
        <!-- 查询条件 -->
        <div class="compact-query">
            <span>盘点单号：</span>
            <el-input v-model="qty_code" class="compact-input" size="small" />
            <span class="compact-label">盘点类型：</span>
            <el-select v-model="qty_type" placeholder="请选择" size="small" class="compact-select">
                <el-option v-for="item in options" :key="item.dict_value" :label="item.dict_label"
                    :value="item.dict_value" />
            </el-select>
            <el-button type="primary" @click="queryZone" size="small">查询</el-button>
            <el-button @click="reset" size="small">重置</el-button>
            <el-button type="primary" @click="addEdit" size="small" class="compact-add-btn">添加</el-button>
            <el-button type="primary" @click="tzEdit" size="small" class="compact-add-btn">冻结仓库</el-button>
        </div>

        <!-- 表格 -->
        <transition name="fade" mode="out-in">
            <div :key="currentPage"> <!-- 添加包裹元素并设置 key -->
                <el-table :data="tableData" :span-method="objectSpanMethod" border class="compact-table"
                    :cell-style="{ padding: '4px 0', textAlign: 'center' }"
                    :header-cell-style="{ padding: '6px 0', textAlign: 'center', background: '#f5f7fa', fontWeight: 'bold' }">
                    <el-table-column prop="qty_code" label="盘点单号" width="120" fixed="left">
                        <template #default="scope">
                            <span class="compact-link" @click="GoQtyInfo(scope.row.qty_code)">{{ scope.row.qty_code
                                }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="qty_type" label="盘点类型" width="90">
                        <template #default="scope"><el-tag size="small">{{ measure_qty_type(scope.row.qty_type)
                                }}</el-tag></template>
                    </el-table-column>
                    <el-table-column prop="qty_audit_status" label="审核状态" width="80">
                        <template #default="scope">
                            <el-tag size="small">{{ getStatusTextStaus(scope.row.qty_audit_status) }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="warehouse_name" label="仓库名称" width="100" />
                    <el-table-column prop="pro_name" label="产品名称" width="90" />
                    <el-table-column prop="pro_code" label="产品编号" width="90" />
                    <el-table-column prop="pro_brand" label="品牌" width="80"><template #default="scope"><el-tag>{{
                                scope.row.pro_brand }}</el-tag></template></el-table-column>
                    <el-table-column prop="pro_model" label="规格型号" width="80" />
                    <el-table-column prop="unit" label="单位" width="70"><template #default="scope"><el-tag
                                size="small">{{
                                measureValue(scope.row.unit) }}</el-tag></template></el-table-column>
                    <el-table-column prop="inventory_numder" label="盘点数量" width="80" />
                    <el-table-column prop="proddti_loss" label="盘亏数量" width="80" />
                    <el-table-column prop="proddti_profit" label="盘盈数量" width="80" />
                    <el-table-column prop="total_loss" label="盘亏总量" width="85" />
                    <el-table-column prop="total_profit" label="盘盈总量" width="85" />
                    <el-table-column prop="qty_clerk" label="盘点人" width="80" />
                    <el-table-column prop="qty_startdate" label="盘点日期" width="90" />
                    <el-table-column fixed="right" label="操作" width="200">
                        <template #default="scope">
                            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                            <el-button size="small" type="warning" @click="handleExamine(scope.row)">审核</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <div class="compact-pagination">
                    <el-pagination size="small" layout="total, sizes, prev, pager, next, jumper"
                        :current-page="currentPage" :page-size="pageSize" :total="pageCount"
                        :page-sizes="[5, 10, 20, 30]" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" />
                </div>
            </div> <!-- 结束包裹元素 -->
        </transition>
        <!-- 审核弹窗 -->
        <el-dialog v-model="centerDialogVisible" width="385" class="compact-dialog" align-center>
            <template #header>
                <div class="compact-dialog-header">审核</div>
            </template>
            <div class="compact-dialog-content">
                <p>审核结果</p>
                <el-radio-group v-model="auditStatus" class="compact-radio-group">
                    <el-radio value="1">通过</el-radio>
                    <el-radio value="2">驳回</el-radio>
                </el-radio-group>
                <p>审核意见</p>
                <el-input v-model="auditOpinion" type="textarea" :autosize="{minRows:3,maxRows:3}" placeholder="请输入"
                    class="compact-textarea" />
            </div>
            <template #footer>
                <div class="compact-dialog-footer">
                    <el-button size="small" @click="close">取消</el-button>
                    <el-button size="small" type="primary" @click="updateAudit">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios, { AxiosError } from 'axios'
import { useRouter } from 'vue-router'
import { useWarehouseStore } from '@/storejs/warehouseStore';
import { ElMessageBox, ElMessage } from 'element-plus';
import dayjs from 'dayjs'

// 搜索字段
const qty_code = ref("")
const qty_type = ref("")
//盘点类型
const options = ref([])

const pageCount = ref(0)//总记录数
// 分页信息
const currentPage = ref(1)
const pageSize = ref(10)

// 表格数据
const tableData = ref([])

//插件路由器实例
var router = useRouter();

const measureOptios = ref([])
const brandOptions = ref([])

//控制审核状态的显示
const centerDialogVisible = ref(false)
const auditStatus = ref('1')//审核状态
const auditOpinion = ref("")//审核意见

//页面跳转
function GoQtyInfo(qty_code) {
    const warehouseStore = useWarehouseStore();
    warehouseStore.qty_code = qty_code;
    router.push('/main/Inv/InvQtyDetails');
}

// 数据转换方法 - 适配盘点数据结构
const transformQtyData = (responseData) => {
    const result = []
    // 计算每个盘点单的总量
 

    responseData.forEach((mainItem) => {
        let totalLoss = 0;
        let totalProfit = 0;

        mainItem.details.forEach(detail => {
            totalLoss += Number(detail.proddti_loss) || 0;
            totalProfit += Number(detail.proddti_profit) || 0;
        });
        mainItem.details.forEach((detail, index) => {
            result.push({
                qty_id: mainItem.qty_id,
                qty_code: mainItem.qty_code,
                qty_type: mainItem.qty_type,
                warehouse_name: mainItem.warehouse_name,
                qty_clerk: mainItem.qty_clerk,
                qty_startdate: formatDate(mainItem.qty_startdate),
                qty_audit_status: mainItem.qty_audit_status,
                qty_audit_opinion: mainItem.qty_audit_opinion,
                pro_name: detail.pro_name,
                pro_code: detail.pro_code,
                pro_brand: detail.pro_brand,
                pro_model: detail.pro_model,
                unit: detail.unitmeas_id,
                inventory_numder: detail.inventory_numder,
                proddti_loss: detail.proddti_loss,
                proddti_profit: detail.proddti_profit,
                total_loss: totalLoss,
                total_profit: totalProfit,
                // 添加一个唯一标识符用于合并判断
                orderGroup: mainItem.qty_code,
                // 添加主单的行数（用于操作列合并）
                rowCount: mainItem.details.length,
                // 添加是否是主单的第一行标志（用于操作列合并）
                isFirstRow: index === 0
            })
        })
    })

    return result
}
//跳转仓库
function tzEdit(){
    router.push('/main/DB/WarehouseInfo');

}

// 日期格式化
const formatDate = (dateString) => {
    if (!dateString) return '';
    try {
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    } catch (error) {
        console.error('日期格式化错误:', error);
        return dateString;
    }
};

// 合并单元格逻辑
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
    // 需要合并的字段（新增两个总量字段）
    const fieldsToMerge = [
        'qty_audit_status',
        'qty_clerk',
        'qty_startdate',
        'qty_code',
        'qty_type',
        'warehouse_name',
        'total_loss',
        'total_profit'
    ];

    // 操作列特殊处理 - 只在第一行显示
    if (columnIndex === 16) { // 注意：列索引增加了2，因为新增了两列
        if (row.isFirstRow) {
            return {
                rowspan: row.rowCount,
                colspan: 1
            };
        } else {
            return {
                rowspan: 0,
                colspan: 0
            };
        }
    }

    // 其他字段的合并逻辑
    if (fieldsToMerge.includes(column.property)) {
        const currentGroup = row.orderGroup;

        // 判断是否是当前组的第一个元素
        if (rowIndex === 0 || tableData.value[rowIndex - 1].orderGroup !== currentGroup) {
            let count = 1;
            for (let i = rowIndex + 1; i < tableData.value.length; i++) {
                if (tableData.value[i].orderGroup === currentGroup) {
                    count++;
                } else {
                    break;
                }
            }
            return { rowspan: count, colspan: 1 };
        } else {
            return { rowspan: 0, colspan: 0 };
        }
    }
};

// 查询计量单位
function getMeasure() {
    axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
            dict_type: "db_measure"
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        measureOptios.value = result.data
        measureOptios.value = [{
            dict_value: "0", dict_label: "请选择单位"
        }, ...result.data]
    }).catch((err) => {
        console.info(err)
    });
}

// 查询品牌字典
function getBrands() {
    axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
            dict_type: "pro_brand"
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        brandOptions.value = result.data
    }).catch((err) => {
        console.info(err)
    });
}


const getStatusTextStaus = (status) => {
    switch (status) {

        case "0": return "审核驳回";
        case "1": return "审核通过";
        default: return "待审核";
    }
}



function measureValue(row) {
    if (!row) return "无";

    // 先尝试在品牌字典中查找
    const brand = brandOptions.value.find((item) => item.dict_value == row);
    if (brand) return brand.dict_label;

    // 再尝试在计量单位字典中查找
    const unit = measureOptios.value.find((item) => item.dict_value == row);
    return unit ? unit.dict_label : "无";
}

// 盘点类型字典转换
function measure_qty_type(row) {
    if (!row) return "无";
    const type = options.value.find((item) => item.dict_value == row);
    return type ? type.dict_label : "无";
}
// const loading = ref(false)
// 请求数据填充表格
function queryZone() {
    // loading.value = true; // 请求开始时设置为 true
    axios.get('http://localhost:5181/api/Inv_Qty/Inv_Qty_selectFY', {
        params: {
            qty_code: qty_code.value,
            qty_type: qty_type.value,
            currentPage: currentPage.value,
            pageSize: pageSize.value
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    })
        .then(async(result) => {
            tableData.value = transformQtyData(result.data)
          
            Count();
            await new Promise(resolve => setTimeout(resolve, 300))
        })
        .catch((err) => {
            console.error(err)
        }).finally(() => {
            // loading.value = false; // 无论成功失败都设置为 false
        });
}

// 获取下拉选项数据 - 盘点类型
function getClassify() {
    axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
            dict_type: "inv_qty"
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        options.value = result.data
    }).catch((err) => {
        console.info(err)
    });
}

//查询总数
function Count() {
    axios.get("http://localhost:5181/api/Inv_qty/Inv_qty_selectCount", {
        params: {
            qty_code: qty_code.value,
            qty_type: qty_type.value,
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`,
        }
    }).then((result) => {
        pageCount.value = result.data
    }).catch((err) => {
        console.info(err)
    })  
}

//获取审核的编码
var qty_code_aduit = ref("");

//点击审核状态继续显示模态框
function handleExamine(row) {
    auditStatus.value=row.qty_audit_status;
    auditOpinion.value =row.qty_audit_opinion;
    if (row.qty_audit_status == "1") {
        ElMessage.info(`订单${row.qty_code}已审核,不可以再次审核`)
    } else {
        //显示 模态框
        centerDialogVisible.value = true;
        qty_code_aduit.value = row.qty_code;
    }
}

//点击修改状态关闭模态框  
function updateAudit() {
    if (auditStatus.value !== "1" && auditStatus.value !== "2") {
        ElMessage.error('请选择审核状态');
        return;
    }
    axios.put("http://localhost:5181/api/Inv_Qty/Inv_qty_examineUpdate",
        {
            qty_code: qty_code_aduit.value,
            qty_audit_status: auditStatus.value,
            qty_audit_by: localStorage.getItem('userLName'),
            qty_audit_opinion: auditOpinion.value,
            qty_audit_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
        },
        {
            headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        }
    ).then((result) => {
        if (result.data > 0) {
            if (auditStatus.value == 1) {
                ElMessage.success('审核通过');
                close();
                Count();
                queryZone();
            } else {
                ElMessage.error('盘点订单驳回');
                close();
                Count();
                queryZone();
            }
        } else {
            ElMessage.error('审核失败');
        }
    }).catch((err) => {
        console.info(err)
    });
}

//盘点单删除
function handleDelete(row) {
    if (row.qty_audit_status == "1") {
        ElMessage.info(`订单${row.qty_code}已审核,不可以进行删除`)
    } else {
        ElMessageBox.confirm(
            `你确定要删除单号为 ${row.qty_code} 的盘点记录吗？`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        ).then(() => {
            axios.put("http://localhost:5181/api/Inv_Qty/Inv_Qty_delete", null, {
                params: { Qty_id: row.qty_id },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                if (result.data > 0) {
                    ElMessage.success('删除成功');
                    Count();
                    queryZone();
                } else {
                    ElMessage.error('删除失败');
                }
            }).catch((err) => {
                console.log(err);
            });
        })
    }
}

//取消审核按钮
function close() {
    centerDialogVisible.value = false
    auditStatus.value = "1"
    auditOpinion.value = ""
}

// 重置查询条件
function reset() {
    qty_code.value = ''
    qty_type.value = ''
    queryZone()
}

// 每页数量变化
const handleSizeChange = (newSize) => {
    pageSize.value = newSize;
    queryZone();
};

// 当前页变化
const handleCurrentChange = (newPage) => {
    currentPage.value = newPage;
    queryZone();
};

// 添加操作
const addEdit = () => {
    
    router.push('/main/Inv/InvQtyAdd');
};

//点击修改进行页面跳转
function handleEdit(row) {
    if (row.qty_audit_status == "1") {
        ElMessage.info(`订单${row.qty_code}已审核,不可以进行修改`)
    } else {
        const warehouseStore = useWarehouseStore();
        warehouseStore.qty_code = row.qty_code;
        router.push('/main/Inv/InvQtyUpdate');
    }
}

// 页面加载时初始化数据
onMounted(() => {
    getClassify()
    getMeasure()
    getBrands()
    queryZone()
    Count()
})
</script>

<style scoped>
.compact-query span {
    font-size: 16px;
    /* 可根据需要调整 */

}

.compact-container {
    padding: 12px;
    font-size: 13px;
}

.compact-query {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 12px;
    margin-top: -30px;
}

.compact-input {
    width: 160px !important;
}

.compact-label {
    margin-left: 8px;
}

.compact-select {
    width: 140px;
}



.compact-table {
    font-size: 12px;
}

.compact-table :deep(.el-table__cell) {
    padding: 4px 0;
}

.compact-table :deep(.el-tag) {
    padding: 0 6px;
    height: 22px;
    line-height: 22px;
    font-size: 12px;
}

.compact-link {
    color: #409EFF;
    cursor: pointer;
}

.compact-pagination {
    margin-top: 12px;
    display: flex;
    justify-content: center;
}

.compact-dialog {
    border-radius: 4px;
}

.compact-dialog-header {
    text-align: left;
    font-size: 14px;
    font-weight: bold;
    padding: 0 0 8px 0;
}

.compact-dialog-content {
    text-align: left;
    padding: 8px 0;
    font-size: 13px;
}

.compact-radio-group {
    margin: 6px 0 12px 16px;
}

.compact-textarea {
    width: 100%;
    margin-top: 6px;
}

.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.2s ease;
}

.fade-enter-from,
.fade-leave-to {
    opacity: 0;
}

.compact-dialog-footer {
    padding-top: 8px;
}
</style>